import os
import shutil

import ddddocr
from PIL import Image
import requests

ocr = ddddocr.DdddOcr(show_ad=False,beta = True)


# # 使用字节流 默认第一套 可能识别不清
# with open('static/yzm/yzm.jpg', 'rb') as f:
#     r = ocr.classification(f.read())
#     print(r)


# # 使用图片base64 需要去除头信息data:image/jpeg;base64
# r = ocr.classification('/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAyAMgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD3+iiigAorzb4ifEu+8J+IdJ0HRtKi1LUb9CRE7lSCzbY8Y9SGznHTqKms/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h5n2W1UrH5jbmwSTyfqTVIeCtAXxWvieOxEWrjO64SRhvBXady5wePbPFAG/RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH//Z')
# print(r)


# # 使用PIL 字节流
# with open('static/yzm/yzm.jpg', 'rb') as f:
#     img = Image.open(f)
#     r = ocr.classification(img)
#     print(r)


# 识别在线图片
res = requests.get("https://www.bjcourt.gov.cn/yzm.jpg",headers={
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36'
})

# 保存图片
directory_path = "static/yzm"
if os.path.exists(directory_path):
    shutil.rmtree(directory_path)
os.makedirs(directory_path)
with open(f'{directory_path}/yzm.jpg', 'wb') as f:
    f.write(res.content)

r = ocr.classification(res.content)
print(r)


